package com.atguigu.orderservice.controller;


import com.atguigu.common.R;
import com.atguigu.common.exception.GuliException;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.common.vo.CommonCourseInfoVo;
import com.atguigu.orderservice.entity.TOrder;
import com.atguigu.orderservice.service.TOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-04-24
 */
@RestController
@RequestMapping("/orderservice/order")
//@CrossOrigin
public class TOrderController {

    @Autowired
    private TOrderService orderService;

    //创建订单
    @PostMapping("createOrder/{courseId}")
    public R createOrders(@PathVariable String courseId, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)) {
            return R.ok().code(28004).message("请先登录");
        }

        //课程id和用户id，返回生成订单id
        String orderId =
                orderService.saveOrders(courseId, memberId );
        return R.ok().data("orderId",orderId);
    }

    //根据订单号查询订单信息
    @GetMapping("getOrderInfo/{orderNo}")
    public R getOrderInfo(@PathVariable String orderNo) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = orderService.getOne(wrapper);
        return R.ok().data("item",order);
    }

    //查询用户是否购买过课程
    @GetMapping("isBuyCourse/{memberId}/{courseId}")
    public boolean isBuyCourse(@PathVariable String memberId,@PathVariable String courseId) {

        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id",memberId);
        wrapper.eq("course_id",courseId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        if(count > 0) {
            return true;
        } else {
            return false;
        }
    }

}

